<template>
  <div class="page">
    <el-row :gutter="16">
      <el-col class="mb-4" :span="6" v-for="(item, index) in list" :key="index">
        <el-card class="task">
          <div class="task-title">{{ item.title }}</div>
          <div>状态：<el-switch v-model="item.isOpen" @change="handSwitch(item)" /></div>
          <div>时间：{{ item.time }}</div>
          <div>计划请求次数：{{ item.total }}</div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ElMessageBox } from 'element-plus'
import { onMounted, ref } from 'vue'
import { taskOpen, taskList, taskOpenedList, taskClose } from '@/api/task'

interface ItemFace {
  name: string
  title: string
  isOpen: boolean
  total: number
  time: string
}
const list = ref<ItemFace[]>()
onMounted(() => {
  initFunc()
})
async function initFunc() {
  try {
    const { data: tList } = await taskList()
    const { data: tOpenedList } = await taskOpenedList()
    tList.forEach((item: ItemFace) => {
      const index = tOpenedList.findIndex((openedItem: ItemFace) => openedItem.name == item.name)
      item.isOpen = index != -1
    })
    list.value = tList
  } catch (error) {
    //
  }
}

const switching = ref(false)
function handSwitch(row: ItemFace) {
  if (switching.value) return
  const tip = row.isOpen ? '打开' : '关闭'
  ElMessageBox({
    title: '系统提示',
    message: `您确定是想要${tip}${row.title}定时任务吗？`,
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        try {
          if (row.isOpen) {
            await taskOpen(row.name)
          } else {
            await taskClose(row.name)
          }
          initFunc()
        } catch (error) {
          row.isOpen = !row.isOpen
        }
        instance.confirmButtonLoading = false
        done()
      } else {
        done()
      }
    }
  })
    .then(() => {})
    .catch(() => {
      row.isOpen = !row.isOpen
    })
}
</script>

<style lang="scss" scoped>
.task {
  font-size: 14px;
  &-title {
    font-size: 16px;
  }
}
</style>
